package com.example.study.page.fragment

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.study.ISort
import com.example.study.databinding.FragmentAIDLBinding

class AIDLFragment : Fragment() {
    private lateinit var binding: FragmentAIDLBinding

    private var array = intArrayOf(5, 2, 8, 3, 1)

    private val connection = object : ServiceConnection {
        private var sorter: ISort? = null
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            sorter = ISort.Stub.asInterface(service)
            try {
                sorter?.sortArray(array)
                binding.text.text = array.joinToString("-")
            } catch (e: RemoteException) {

            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            sorter = null
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentAIDLBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.text.text = array.joinToString("-")
        binding.button.setOnClickListener {
            val intent = Intent("com.example.study.ISort")
            intent.setPackage(context?.applicationContext?.packageName)
            activity?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        activity?.unbindService(connection)
    }

}